package com.rockymew.core.utility.http;

import java.io.IOException;
import java.io.InputStream;

import okhttp3.MediaType;

public class HttpFileInputStream extends InputStream {

    public HttpFileInputStream(InputStream input, okhttp3.MediaType contentType, int content_length, String filename) {
        this.input = input;
        this.length = content_length < 0 ? -1 : content_length;
        this.contentType = contentType;
        this.filename = filename;
    }

    private InputStream input;
    private MediaType contentType;
    @SuppressWarnings("unused")
    private int length = 0;
    private String filename;

    public String getFilename() {
        return this.filename;
    }

    public void setFilename(String filename) {
        this.filename = filename;
    }

    public MediaType getContentType() {
        return this.contentType;
    }

    public void setContentType(MediaType contentType) {
        this.contentType = contentType;
    }

    public String filenameSuffix() {
        if (null != this.filename && !this.filename.isEmpty()) {
            int pos = this.filename.lastIndexOf(".");
            if (pos != -1 && pos != this.filename.length() - 1) {
                return this.filename.substring(pos + 1).toLowerCase();
            }
        }
        if (null != this.contentType) {
            MediaType type = this.contentType;
            if (type.type().equals("image")) {
                if (type.subtype().equals("image/gif")) {
                    return "gif";
                } else if (type.subtype().equals("image/png")) {
                    return "png";
                } else if (type.subtype().equals("image/jpeg")) {
                    return "jpg";
                } else if (type.subtype().equals("image/bmp")) {
                    return "bmp";
                }
            }
        }

        return "";
    }

    @Override
    public int read() throws IOException {
        // TODO Auto-generated method stub
        return this.input.read();
    }

    @Override
    public void close() throws IOException {
        this.input.close();
    }

    @Override
    public int available() throws IOException {
        return input.available();
    }

    @Override
    protected void finalize() throws Throwable {
        close();
    }
    
    @Override
    public long skip(long n) throws IOException {
        return input.skip(n);
    }
    
    @Override
    public synchronized void reset() throws IOException {
        input.reset();
    }
    
    @Override
    public synchronized void mark(int readlimit) {
        input.mark(readlimit);
    }
    
    @Override
    public boolean markSupported() {
        return input.markSupported();
    }
    
}